package com.example.mydy.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mydy.R;
import com.example.mydy.model.RewardTask;
import com.example.mydy.utils.ImageLoader;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 可接取悬赏任务的列表适配器
 */
public class AvailableRewardAdapter extends RecyclerView.Adapter<AvailableRewardAdapter.ViewHolder> {

    private List<RewardTask> rewardTasks;
    private OnRewardClickListener listener;

    public interface OnRewardClickListener {
        void onRewardClick(RewardTask rewardTask);
        void onTakeRewardClick(RewardTask rewardTask);
    }

    public AvailableRewardAdapter(List<RewardTask> rewardTasks, OnRewardClickListener listener) {
        this.rewardTasks = rewardTasks;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_available_reward, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        RewardTask task = rewardTasks.get(position);
        
        // 设置任务标题和描述
        holder.titleTextView.setText(task.getTitle());
        holder.descriptionTextView.setText(task.getDescription());
        
        // 设置奖励金额
        holder.rewardAmountTextView.setText(String.format(Locale.getDefault(), "￥%.2f", task.getReward()));
        
        // 设置剩余数量
        holder.remainingOrdersTextView.setText(String.format(Locale.getDefault(), "剩余: %d", task.getRemainingOrders()));
        
        // 设置已接取人数
        holder.earnedPeopleTextView.setText(String.format(Locale.getDefault(), "已接取: %d人", task.getEarnedPeople()));
        
        // 设置截止日期，如果有的话
        if (task.getDeadline() != null && !task.getDeadline().isEmpty()) {
            Date deadlineDate = task.getDeadlineAsDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            holder.deadlineTextView.setText(String.format("截止日期: %s", sdf.format(deadlineDate)));
            
            // 计算剩余天数并显示
            int daysLeft = getDaysLeft(deadlineDate);
            if (daysLeft > 0) {
                holder.daysLeftTextView.setVisibility(View.VISIBLE);
                holder.daysLeftTextView.setText(String.format("剩余%d天", daysLeft));
                
                // 如果剩余不到3天，显示红色
                if (daysLeft <= 3) {
                    holder.daysLeftTextView.setTextColor(holder.itemView.getContext().getResources().getColor(R.color.colorError));
                } else {
                    holder.daysLeftTextView.setTextColor(holder.itemView.getContext().getResources().getColor(R.color.colorPrimary));
                }
            } else {
                holder.daysLeftTextView.setVisibility(View.GONE);
            }
        } else {
            holder.deadlineTextView.setText("长期任务");
            holder.daysLeftTextView.setVisibility(View.GONE);
        }
        
        // 设置标签
        holder.tagChipGroup.removeAllViews();
        if (task.getTags() != null && !task.getTags().isEmpty()) {
            for (String tag : task.getTags()) {
                Chip chip = new Chip(holder.itemView.getContext());
                chip.setText(tag);
                chip.setCheckable(false);
                chip.setClickable(false);
                holder.tagChipGroup.addView(chip);
            }
        }
        
        // 加载任务图片
        if (task.getImageUrl() != null && !task.getImageUrl().isEmpty()) {
            holder.taskImageView.setVisibility(View.VISIBLE);
            ImageLoader.loadImage(holder.itemView.getContext(), task.getImageUrl(), holder.taskImageView);
        } else {
            holder.taskImageView.setVisibility(View.GONE);
        }
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onRewardClick(task);
            }
        });
        
        // 设置接取按钮点击事件
        holder.takeButton.setOnClickListener(v -> {
            if (listener != null) {
                listener.onTakeRewardClick(task);
            }
        });
        
        // 如果没有剩余名额，禁用接取按钮
        if (task.getRemainingOrders() <= 0) {
            holder.takeButton.setEnabled(false);
            holder.takeButton.setText("已满额");
        } else {
            holder.takeButton.setEnabled(true);
            holder.takeButton.setText("接取任务");
        }
    }

    @Override
    public int getItemCount() {
        return rewardTasks.size();
    }
    
    /**
     * 更新数据
     */
    public void updateData(List<RewardTask> newData) {
        this.rewardTasks = newData;
        notifyDataSetChanged();
    }
    
    /**
     * 计算截止日期还剩多少天
     */
    private int getDaysLeft(Date deadlineDate) {
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);
        
        Calendar deadline = Calendar.getInstance();
        deadline.setTime(deadlineDate);
        deadline.set(Calendar.HOUR_OF_DAY, 0);
        deadline.set(Calendar.MINUTE, 0);
        deadline.set(Calendar.SECOND, 0);
        deadline.set(Calendar.MILLISECOND, 0);
        
        long diff = deadline.getTimeInMillis() - today.getTimeInMillis();
        return (int) (diff / (24 * 60 * 60 * 1000));
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView titleTextView;
        TextView descriptionTextView;
        TextView rewardAmountTextView;
        TextView remainingOrdersTextView;
        TextView earnedPeopleTextView;
        TextView deadlineTextView;
        TextView daysLeftTextView;
        ChipGroup tagChipGroup;
        ImageView taskImageView;
        Button takeButton;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.tv_task_title);
            descriptionTextView = itemView.findViewById(R.id.tv_task_description);
            rewardAmountTextView = itemView.findViewById(R.id.tv_reward_amount);
            remainingOrdersTextView = itemView.findViewById(R.id.tv_remaining_orders);
            earnedPeopleTextView = itemView.findViewById(R.id.tv_earned_people);
            deadlineTextView = itemView.findViewById(R.id.tv_deadline);
            daysLeftTextView = itemView.findViewById(R.id.tv_days_left);
            tagChipGroup = itemView.findViewById(R.id.chip_group_tags);
            taskImageView = itemView.findViewById(R.id.iv_task_image);
            takeButton = itemView.findViewById(R.id.btn_take_task);
        }
    }
} 